package ru.gr.alphaversion;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ItemList extends ListActivity {

	public static CL_Adapter cl_adapter;
	public ArrayList cl_tovars = null;
	final int MENU_ITEM_DELETE = 200;
	final int MENU_ITEM_CHANGE = 201;

	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.item_list);
        Main.checkk = 0;
        cl_tovars = Main.cl_tovars_main;//new ArrayList();
        cl_adapter = new CL_Adapter(this, R.layout.cl_list_item, cl_tovars);
        setListAdapter(cl_adapter); 
        registerForContextMenu(getListView());
    //    TextView id_l = (TextView)findViewById(R.id.e_id);
     //   id_l.setText(Main.list_id);
        cl_adapter.notifyDataSetChanged();
     //   finalSum();
    }
	
	
	protected void onResume() {
		super.onResume();
		cl_adapter.notifyDataSetChanged();
		Main.checkk = 0;
	//	TextView id_l = (TextView)findViewById(R.id.e_id);
		//id_l.setText(Main.list_id);
	//	finalSum();
	}
	
	public class CL_Adapter extends ArrayAdapter {

		private ArrayList listitems;

		public CL_Adapter(Context context, int textViewResourceId, ArrayList items) {
	        super(context, textViewResourceId, items);
	        this.listitems = items;
		}

		@Override
	    public View getView(int position, View convertView, ViewGroup parent) {
	        View v = convertView;
	        if (v == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		        v = vi.inflate(R.layout.cl_list_item, null);
	            }
	            CL_ListItem cl_item = (CL_ListItem) listitems.get(position);
	            if (cl_item != null) {
	                TextView tname = (TextView) v.findViewById(R.id.cl_tovarname);
	                TextView tcena = (TextView) v.findViewById(R.id.cl_tovarcena);
	                TextView tid = (TextView) v.findViewById(R.id.tovarid);
	                TextView tsum= (TextView) v.findViewById(R.id.tovarsum);
	                //TextView tost = (TextView) v.findViewById(R.id.cl_tovarost);
	                TextView quantity = (TextView) v.findViewById(R.id.quantity);
	                if (tname != null) {
	                    tname.setText(cl_item.getTovar_name());
	                }
	                else { 
	                	tname.setText("Error tovar name!"); 
	                }
	                if (tid != null) {
	                    tid.setText(cl_item.getTovar_id());
	                }
	                else { 
	                	tid.setText("Error tovar id!"); 
	                }
	                if (tcena != null) {
	                    tcena.setText(cl_item.getTovar_cena());
	                }
	               /* if (tost != null) {
	                    tost.setText(cl_item.getTovar_ost());
	                }*/
	                
	                if (quantity != null) {
	                	quantity.setText(Integer.toString(Integer.parseInt(cl_item.getTovar_quantity())));
	                	float k = 0;
	                	k += Float.parseFloat(cl_item.getTovar_cena())*Float.parseFloat(cl_item.getTovar_quantity());
	                	k = k*100;
	            		k = Math.round(k);
	            		k = k/100;
	                	tsum.setText(Float.toString(k));
	                } 
	                
	            }
	            else {
					TextView tname = (TextView) v.findViewById(R.id.cl_tovarname);
					tname.setText("No item!");
				}
	            return v;
	    }
	}
	
	public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
		menu.setHeaderTitle("Действия");   
		menu.add(0, MENU_ITEM_CHANGE, 0, "Изменить количество");
		menu.add(0, MENU_ITEM_DELETE, 0, "Удалить товар");
		}
	
	public boolean onContextItemSelected (MenuItem item) {
		switch (item.getItemId()) {
		case MENU_ITEM_DELETE:
	       AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	       int id = (int) this.getListView().getItemIdAtPosition(info.position);
	       //Log.d("123", "Item ID at POSITION:"+id);
	       Main mn = new Main();
	       mn.delItem(id);
	       cl_adapter.notifyDataSetChanged();
	    //   finalSum();
	       return true;
		case MENU_ITEM_CHANGE:
			AdapterContextMenuInfo info1 = (AdapterContextMenuInfo) item.getMenuInfo();
			final int id1 = (int) this.getListView().getItemIdAtPosition(info1.position);		    
		    final GetJSON json = new GetJSON();
			final EditText editText = new EditText(this);
			editText.setInputType(InputType.TYPE_CLASS_NUMBER);
			new AlertDialog.Builder(this)
			.setTitle("Введите количество товара")
			.setView(editText)
			.setNegativeButton(android.R.string.no, null)
	        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					if(isNumeric(editText.getText().toString())) {
						Main mn1 = new Main();
						if (mn1.changeItem(id1, editText.getText().toString()))
						{cl_adapter.notifyDataSetChanged();}
						else {
							Toast toast = Toast.makeText(ItemList.this, "Неверное количество товара", Toast.LENGTH_LONG);
			    			toast.setGravity(Gravity.CENTER, 0, 0);
			    			toast.show();
						}
						//finalSum();
					}
				}
			})
	            .create().show();
		    cl_adapter.notifyDataSetChanged();
		    //cl_adapter.notifyAll();
			return true;
		default:
            return super.onOptionsItemSelected(item);
		}
	}
	
	public static boolean isNumeric(String str)  
    {  
      try  
      {  
        Double.parseDouble(str);  
      }  
      catch(NumberFormatException nfe)  
      {  
        return false;  
      }  
      return true;  
    }
	
	
    
	
	
	@Override
    public void onBackPressed() {
		
    }
	
	/*public void finalSum() {
		float k = 0;
		if(cl_tovars.size()!=0){
			for (int i=cl_tovars.size()-1;i>=0;i--) {
				CL_ListItem cl_row = (CL_ListItem) cl_tovars.get(i);
				k += Float.parseFloat(cl_row.getTovar_cena())*Double.parseDouble(cl_row.getTovar_quantity());
			}
		}
		TextView tv = (TextView)findViewById(R.id.e_sum);
		
		k = k*100;
		k = Math.round(k);
		k = k/100;
		//Math.rint(k);
		tv.setText(Float.toString(k));
				
	}
*/
	/*public void getCLtovars(String item){
		   //РѕС‡РёСЃС‚РёРј СЃРїРёСЃРѕРє РѕС‚ РїСЂРµРґС‹РґСѓС‰РёС… Р·РЅР°С‡РµРЅРёР№
		        //cl_tovars.clear();
		       // for(int i=0; i<5; i++){
		    	CL_ListItem cl_row = new CL_ListItem();
		        	cl_row.setTovar_name(item);
		        	cl_row.setTovar_cena(Double.toString(1.01*1));
		        	cl_row.setTovar_ost(Integer.toString(1));
		        	cl_tovars.add(cl_row);  //РґРѕР±Р°РІРёРј СЌР»РµРјРµРЅС‚
		        //}
		       //СЃРѕРѕР±С‰РёРј Р°РґР°РїС‚РµСЂСѓ, С‡С‚Рѕ РґР°РЅРЅС‹Рµ РёР·РјРµРЅРёР»РёСЃСЊ
		        cl_adapter.notifyDataSetChanged();
			}*/
}